<template>
  <div class="file-upload">
    <div class="file-upload-container" @click.prevent="triggerUpload" v-bind="$attrs">
      <!-- 上传组件自定义模板 -->
      <slot v-if="fileStatus === 'loading'" name="loading">
        <button class="btn btn-primary" disabled>正在上传中，请稍候</button>
      </slot>
      <!-- slot中传递数据 -->
      <slot v-else-if="fileStatus === 'success'" name="uploaded" :uploadedData="uploadedData">
        <button class="btn btn-primary">上传成功</button>
      </slot>
      <slot v-else name="default">
        <button class="btn btn-primary">点击上传</button>
      </slot>
    </div>
    <input
      type="file"
      class="file-input d-none"
      ref="fileInput"
      @change.prevent="handleFileChange"
    />
  </div>
</template>

<script lang="ts">
import axios from 'axios'
import { defineComponent, PropType, ref, watch } from 'vue'

// 上传文件的状态
type UploadStatus = 'ready' | 'loading' | 'success' | 'error'
// 文件校验函数类型
type CheckFunction = (file: File) => boolean
export default defineComponent({
  name: 'Uploader',
  props: {
    action: {
      type: String,
      required: true
    },
    beforeUpload: {
      type: Function as PropType<CheckFunction>
    },
    // 用于判断文件图片是新增还是修改
    uploaded: {
      type: Object
    }
  },
  inheritAttrs: false,
  emits: ['file-uploaded', 'file-uploaded-error'],
  setup (props, context) {
    // 获取input节点
    const fileInput = ref<null | HTMLInputElement>(null)
    const fileStatus = ref<UploadStatus>(props.uploaded ? 'success' : 'ready')
    const uploadedData = ref(props.uploaded)
    // 监听属性uploaded值的变化，更新文件上传的状态和上传的文件数据(url)
    watch(() => props.uploaded, (newValue) => {
      if (newValue) {
        fileStatus.value = 'success'
        uploadedData.value = newValue
      }
    })
    // 触发文件上传输入框点击
    const triggerUpload = () => {
      if (fileInput.value) {
        // 点击input节点
        fileInput.value.click()
      }
    }
    // 上传文件图片处理
    const handleFileChange = (e: Event) => {
      // 获取上传文件的信息
      const currentTarget = e.target as HTMLInputElement
      // 已经选择了上传的文件
      if (currentTarget.files) {
        const files = Array.from(currentTarget.files) // 类数组转换为数组
        // 上传文件校验
        if (props.beforeUpload) {
          const result = props.beforeUpload(files[0])
          if (!result) {
            return
          }
        }
        fileStatus.value = 'loading'
        // 添加要发送的文件名和数据, 然后上传文件
        const formData = new FormData()
        formData.append('file', files[0]) // 获取第一文件,只能单文件上传
        axios.post(props.action, formData, {
          headers: {
            'Content-Type': 'multipart/form-data' // 设置文件上传的格式
          }
        }).then(resp => {
          fileStatus.value = 'success'
          uploadedData.value = resp.data
          context.emit('file-uploaded', resp.data)
        }).catch((e) => {
          fileStatus.value = 'error'
          context.emit('file-uploaded-error', e)
        }).finally(() => {
          if (fileInput.value) {
            fileInput.value.value = ''
          }
        })
      }
    }
    return {
      fileInput,
      triggerUpload,
      fileStatus,
      handleFileChange,
      uploadedData
    }
  }
})
</script>
